from torch.utils.tensorboard import SummaryWriter
from torchvision import transforms
from PIL import Image
import os

img_path = "dataset/train/ants/0013035.jpg"
img = Image.open(img_path)

print(img)
# 转换为 tensor 
# ToTensor
transform = transforms.ToTensor()
img_tensor = transform(img)

print(img_tensor)

writer = SummaryWriter("logs")
writer.add_image("tensor_image", img_tensor)

# Normalize 归一化
# 公式：output[channel] = (input[channel] - mean[channel]) / std[channel]
# 归一化到 [0, 1]
trans_norm = transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
img_norm = trans_norm(img_tensor)
print(img_norm[0][0][0])

writer.add_image("norm_image", img_norm)

# 缩放
trans_resize = transforms.Resize((512, 512))
img_resize = trans_resize(img_norm)
print(img_resize)

writer.add_image("resize_image", img_resize)

# Compose - resize - 2 
# 在Compose中应该放入transform对象而不是tensor
trans_compose = transforms.Compose([transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor()])
img_compose = trans_compose(img)
writer.add_image("Compose", img_compose, 1)

# RandomCrop 随机裁剪
trans_random = transforms.RandomCrop(224)
trans_compose_random = transforms.Compose([trans_random, transforms.ToTensor()])

for i in range(10):
    img_compose_random = trans_compose_random(img)
    writer.add_image("RandomCrop", img_compose_random, i)

writer.close()